package com.ruoyi.merchant.utils;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ysq
 * @Date: 2024/09/12/16:29
 * @Description: 通过地理位置，获取到详细的经纬度
 */

import com.alibaba.fastjson2.JSON;
import com.ruoyi.merchant.utils.list.ReturnLocationBean;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

public class GeocodingUtil {
    private static final Logger log = LoggerFactory.getLogger(GeocodingUtil.class);
    public static final String URL = "http://api.map.baidu.com/geocoding/v3/?output=json&location=showLocation";
    public static final String AK = "Ii3HkL7yqlBRMf5YtDAwjg7CXpISDk8L";
    /**
     * 根据地址获取经纬度
     * @param address 详细的位置信息，例如“广东省广州市黄埔区”
     * @return 返回位置的封装对象
     */
    public ReturnLocationBean addressToLongitude(String address) {
        String url = URL + "&ak=" + AK + "&address=" + encodeAddress(address);
        //log.info("请求url: " + url);
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String responseText = EntityUtils.toString(entity);
            //log.info("返回信息: " + responseText);
            // JSON 转对象
            return JSON.parseObject(responseText, ReturnLocationBean.class);
        } catch (Exception e) {
            //log.error("地理编码[异常]:", e);
            return null;
        }
    }

    /**
     * 对地址进行 URL 编码
     * @param address 要编码的地址
     * @return 编码后的地址
     */
    private String encodeAddress(String address) {
        try {
            return java.net.URLEncoder.encode(address, "UTF-8");
        } catch (Exception e) {
            //log.error("地址编码失败:", e);
            return address; // 如果编码失败，返回原地址
        }
    }
}
